package com.ts.office;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

/**
 * 针对金格office插件工具类
 * Created by xhc on 2017-3-23.
 */
public class SysOffice {
    private Hashtable<String, String> saveFormParam = new Hashtable<String, String>(); // 保存form表单数据

    //文件流
    private InputStream fileContentStream;
    //文件名称
    private String fileName = "";
    //文件内容
    private byte[] mFileBody = null;
    //是否已经加载文件
    private boolean isLoadFile = false;
    private String sendType = "";

    private static final String MsgError = "404"; // 设置常量404，说明没有找到对应的文档

    public String getSendType() {
        return sendType;
    }

    public void setSendType(String sendType) {
        this.sendType = sendType;
    }

    /**
     * 获取文件流 add by xhc
     *
     * @return
     */
    public InputStream getContentStream() {
        return this.fileContentStream;
    }

    /**
     * @throws FileUploadException
     * @throws IOException
     * @deprecated:后台类解析接口
     * @time:2015-01-09
     */
    public void load(HttpServletRequest request) throws FileUploadException,
            IOException {
        request.setCharacterEncoding("gb2312");
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(
                diskFileItemFactory);
        List<FileItem> fileList = fileUpload.parseRequest(request);
        Iterator<FileItem> iter = fileList.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            // 如果是字段
            if (item.isFormField()) {
                processFormField(item);
            } else {
                // 如果是二进制流
                processUploadedFile(item);
            }
        }
    }

    /**
     * @param item :表单数据
     * @throws UnsupportedEncodingException
     * @deprecated：解析表达数据
     * @time:2015-01-09
     */
    public void processFormField(FileItem item)
            throws UnsupportedEncodingException {
        String fieldName = item.getFieldName();
        String fieldValue = "";
        fieldValue = item.getString("utf-8");
        if (this.sendType.equalsIgnoreCase("JSON")) {
            JSONObject json = JSONObject.parseObject(fieldValue);
            Iterator iter = json.keySet().iterator();
            while (iter.hasNext()) {
                fieldName = (String) iter.next();
                fieldValue = json.getString(fieldName);
                saveFormParam.put(fieldName, fieldValue);
            }
            return;
        }
        saveFormParam.put(fieldName, fieldValue);
    }

    /**
     * @param item :文档数据
     * @throws IOException
     * @throws UnsupportedEncodingException
     * @deprecated：解析文档数据
     * @time:2015-01-09
     */
    public void processUploadedFile(FileItem item) throws IOException {
        fileName = item.getName();
        if (fileName.indexOf("/") >= 0) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        } else if (fileName.indexOf("\\") >= 0) {
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
        }
        fileContentStream = item.getInputStream();

    }

    /**
     * @param fieldName :参数名称
     * @deprecated：解析文档数据
     * @return：参数对于的值
     * @time:2015-01-09
     */
    public String getMsgByName(String fieldName) {
        return saveFormParam.get(fieldName);
    }

    /**
     * 清除所有SetMsgByName所有内容
     *
     * @time:2015-01-09
     */
    public void msgTextClear() {
        saveFormParam.clear();
    }

    public byte[] msgFileBody() throws IOException {
        mFileBody = null;
        isLoadFile = false;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = fileContentStream.read(buffer))) {
            output.write(buffer, 0, n);
        }
        mFileBody = output.toByteArray();
        return mFileBody;
    }

    /**
     * 把字节数组保存为一个文件
     *
     * @param outputFile
     * @return
     */
    public boolean msgFileSave(String outputFile) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        try {
            File f = new File(outputFile);
            int BUFFER_SIZE = 1024;
            byte[] buf = new byte[BUFFER_SIZE];
            int size = 0;
            bis = new BufferedInputStream(fileContentStream);
            fos = new FileOutputStream(f);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 本地文件加载
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public boolean msgFileLoad(String fileName) throws Exception {
        try {
            File file = new File(fileName);
            if (file.exists()) {
                fileContentStream = new FileInputStream(new File(fileName));
                msgFileBody();
            } else {
                mFileBody = new byte[0];
            }
            isLoadFile = true;
        } catch (Exception e) {
            throw e;
        } finally {
            if (fileContentStream != null) {
                fileContentStream.close();
            }
        }
        return true;
    }

    /**
     * 二进制流加载方式 add by xhc
     *
     * @param fis
     * @return
     * @throws IOException
     */
    public boolean msgStreamLoad(FileInputStream fis) throws Exception {
        try {
            fileContentStream = fis;
            msgFileBody();
            isLoadFile = true;
        } catch (Exception e) {
            throw e;
        } finally {
            if (fileContentStream != null) {
                fileContentStream.close();
            }
        }
        return true;
    }

    /**
     * 字节数组加载方式 add by xhc
     *
     * @param bts
     * @return
     * @throws IOException
     */
    public boolean msgByteLoad(byte[] bts) throws IOException {
        if (bts != null) {
            isLoadFile = true;
            mFileBody = bts;
        }
        return true;
    }

    /**
     * @param response
     * @throws IOException
     * @deprecated:将文件的二进制数据设置到信息包中
     */
    public void send(HttpServletResponse response) throws IOException {
        try {
            if (isLoadFile) {
                if (mFileBody.length != 0) {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/x-msdownload;charset=utf-8");
                    response.setContentLength(mFileBody.length);
                    response.setHeader("Content-Disposition", "attachment;filename=");
                    response.getOutputStream().write(mFileBody, 0, mFileBody.length);
                } else {
                    response.setHeader("MsgError", "404");
                }
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            // e.printStackTrace();
        }
    }
}
